package com.woshengqile.api.controller;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.i18n.I18n;
import com.jfinal.i18n.Res;
import com.woshengqile.Setting;
import com.woshengqile.api.common.bean.BaseResponse;
import com.woshengqile.api.common.bean.Code;
import com.woshengqile.api.common.bean.DataResponse;
import com.woshengqile.api.common.bean.Require;
import com.woshengqile.interceptor.CsrfInterceptor;
import com.woshengqile.model.VideoInfo;
import com.woshengqile.model.VideoInfoCategory;
import com.woshengqile.shiro.core.ShiroInterceptor;
import com.woshengqile.util.EnumUtils;
import com.woshengqile.util.SystemUtils;

import cn.hutool.core.collection.CollectionUtil;
/**
 * 
 * 移动API - Base
 *
 */
@Clear({CsrfInterceptor.class, ShiroInterceptor.class})
public class BaseAPIController extends Controller {

	/** 返回图片地址 */
	protected Setting setting = SystemUtils.getSetting();
	
	protected Res res = I18n.use();
	
    /**
	 * 枚举类型转换
	 * 
	 */
	public <T> T getParaEnum(Class<T> clazz, String value) {
		return (T) EnumUtils.convert(clazz, value);
	}
	
    /**
     * 响应接口不存在*
     */
    public void render404() {
        renderJson(new BaseResponse(Code.NOT_FOUND));      
    }

    /**
     * 响应请求参数有误*
     * @param message 错误信息
     */
    public void renderArgumentError(String message) {
        renderJson(new BaseResponse(Code.ARGUMENT_ERROR, message));
    }

    /**
     * 响应数组类型*
     * @param list 结果集合
     */
    public void renderDataResponse(List<?> list) {
        DataResponse resp = new DataResponse();
        resp.setDatum(list);
        if (CollectionUtils.isEmpty(list)) {
            resp.setMessage("未查询到数据");
        } else {
            resp.setMessage("success");
        }
        renderJson(resp);
    }

    /**
     * 响应操作成功*
     * @param message 响应信息
     */
    public void renderSuccess(String message) {
        renderJson(new BaseResponse().setMessage(message));        
    }

    /**
     * 响应操作失败*
     * @param message 响应信息
     */
    public void renderFailed(String message) {
        renderJson(new BaseResponse(Code.FAIL, message));    
    }
    
    /**
     * 判断参数值是否为空
     * @param rules
     * @return
     */
    public boolean notNull(Require rules) {
        if (rules == null || rules.getLength() < 1) {
            return true;
        }

        for (int i = 0, total = rules.getLength(); i < total; i++) {
            Object key = rules.get(i);
            String message = rules.getMessage(i);
            BaseResponse response = new BaseResponse(Code.ARGUMENT_ERROR);
            
            if (key == null) {
                renderJson(response.setMessage(message));
                return false;
            }

            if (key instanceof String && StringUtils.isEmpty((String) key)) {
                renderJson(response.setMessage(message));
                return false;
            }

            if (key instanceof Array) {
                Object[] arr = (Object[]) key;

                if (arr.length < 1) {
                    renderJson(response.setMessage(message));
                    return false;
                }
            }
        }
        return true;
    }
    
    /**
     * 判断请求类型是否相同
     * @param name
     * @return
     */
    protected boolean methodType(String name) {
        return getRequest().getMethod().equalsIgnoreCase(name);
    }
    
    /**
	 * 货币格式化
	 * @param amount 金额
	 * @param showSign 显示标志
	 * @param showUnit 显示单位
	 * @return 货币格式化
	 */
	protected String currency(BigDecimal amount, boolean showSign, boolean showUnit) {
		Setting setting = SystemUtils.getSetting();
		String price = setting.setScale(amount).toString();
		if (showSign) {
			price = setting.getCurrencySign() + price;
		}
		if (showUnit) {
			price += setting.getCurrencyUnit();
		}
		return price;
	}
	
	/**
	 * 将String数组转换为Long类型数组
	 * 
	 */
	protected Long[] convertToLong(String name) {
		String[] values = StringUtils.split(name, ",");
		if (values == null)
			return null;
		Long[] result = new Long[values.length];
		for (int i=0; i<result.length; i++)
			result[i] = Long.parseLong(values[i]);
		return result;
	}
	
	/**
	 * 转换为前端所需格式
	 * @param videoCategories
	 */
	protected void convertVideoCategory(List<VideoInfoCategory> videoInfoCategories) {
		if (CollectionUtil.isNotEmpty(videoInfoCategories)) {
			for (VideoInfoCategory videoInfoCategory : videoInfoCategories) {
				videoInfoCategory.put("id_str", String.valueOf(videoInfoCategory.getId()));
			}
		}
	}
	
	/**
	 * 视频信息转换为前端所需格式
	 * @param videoInfos
	 */
	protected void convertVideoInfo(List<VideoInfo> videoInfos) {
		if (CollectionUtil.isNotEmpty(videoInfos)) {
			for (VideoInfo videoInfo : videoInfos) {
				videoInfo.put("id_str", String.valueOf(videoInfo.getId()));
				videoInfo.put("category_list", videoInfo.getCategorys());
				videoInfo.put("tag_list", videoInfo.getTags());
			}
		}
	}

}
